//
//  UIColor_ZZ.swift
//  KeDaLeDaoHang
//
//  Created by 陈钟 on 2019/5/10.
//  Copyright © 2019 陈钟. All rights reserved.
//

import Foundation
import UIKit

public extension UIColor{

    @objc static func hexColor(hexStr:String ,alpha:CGFloat) -> UIColor {
        var cString = hexStr.trimmingCharacters(in: CharacterSet.whitespaces).uppercased()
        if (cString.count < 6){
            return UIColor.clear
        }
        if (cString.hasPrefix("0X")) {
            cString = cString.substring(from: 2)
        }
        if (cString.hasPrefix("#")) {
            cString = cString.substring(from: 1)
        }
        if cString.count != 6 {
            return UIColor.clear
        }
        var range = NSRange.init(location: 0, length: 2)
        
        //R
        let rString = cString.substring(range: range)
        //G
        range.location = 2
        let gString = cString.substring(range: range)
        //B
        range.location = 4
        let bString = cString.substring(range: range)
        
        var r:CUnsignedLongLong = 0, g:CUnsignedLongLong = 0, b:CUnsignedLongLong = 0;

        Scanner.init(string: rString).scanHexInt64(&r)
        Scanner.init(string: gString).scanHexInt64(&g)
        Scanner.init(string: bString).scanHexInt64(&b)
        
        return UIColor(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: alpha)
    }
    /// HEXColor
    @objc static func hexColor(hexStr:String) -> UIColor {
        return hexColor(hexStr: hexStr, alpha: 1)
    }
    /// HEXColor
    @objc static func hexStr(_ hexStr:String) -> UIColor {
        return hexColor(hexStr: hexStr, alpha: 1)
    }
    ///  获取颜色的RGB
    func getRGB() -> (r:CGFloat,g:CGFloat,b:CGFloat,a:CGFloat) {
        var red = CGFloat()
        var green = CGFloat()
        var blue = CGFloat()
        var alpha = CGFloat()
        self.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
        return(red,green,blue,alpha)
    }
    
    /// 修改颜色的透明度
    @objc static func changeAlpha(color:UIColor,alpha:CGFloat) -> UIColor {
        let rgb = color.getRGB()
        return UIColor.init(red: rgb.r, green: rgb.g, blue: rgb.b, alpha: alpha)
    }
    /// 修改颜色的透明度
    @objc func changeAlpha(_ alpha:CGFloat) -> UIColor {
        return UIColor.changeAlpha(color: self, alpha: alpha)
    }
}
